<?php
	namespace Qzn\Model;
	require_once('./Model/validate.php');
	require_once('./Model/Hash/hashConfig.php');
	require_once('./Model/Hash/PasswordHash.php');

	class ProfileHandler {
		const EVERYTHING_WENT_BETTER_THEN_EXPECTED = 0;
		const INVALID_OLD_PASSWORD = 1;
		const INVALID_NEW_PASSWORD = 2;
		const INVALID_NEW_PASSWORD_NO_MATCH = 3;
		const INVALID_USER = 4;
					
		private $m_db = null;
		private $m_profilePath = "./ProfilePic/default.jpg";
		
		public function __construct(Database $db) {
			$this->m_db = $db;
		}
		
		/**
		 * Gets an array of usernames
		 * @return array $ml
		 */
		public function GetProfileData ($userPk) {
			$pd =  DatabaseQuery::SelectProfileData($userPk, $this->m_db);			
			
			return $pd;
		}
		
		/**
		 * Gets an array of usernames
		 * @return array $ml
		 */
		public function GetPicturePath ($userPk) {
			$pp =  DatabaseQuery::SelectProfilePicture($userPk, $this->m_db);
			
			return $pp == null ? $this->m_profilePath : $pp;
		}
		

		/**
		 * @return boolean
		 */
		public function ChangePassword (\Qzn\View\ProfileView $pw, \Qzn\View\LoginView $lw) {
			$v = new Validate();
			$pwo = $pw->GetOldPasswordText();
			$pwn = $pw->GetNewPasswordText();
			$pwna = $pw->GetNewPasswordTextAgain();
			$hash = null;
			$hasher = null;
			$hashConfig = null;
			
			if ($v->ValidatePassword($pwn)) {
				if ($pwn === $pwna) {
					$userPk = $lw->GetUserPk();
					if ($userPk == \Qzn\View\NavigationView::getProfilePk()) {
						$hash = DatabaseQuery::GetPassword($userPk, $this->m_db);
						$hash = $hash[0];
						$hashConfig = new \hashConfig();
						$hasher = new \PasswordHash($hashConfig);
						$success = $hasher->CheckPassword($pwo, $hash);
						if ($success) {
							$hash = $hasher->HashPassword($pwn);
							DatabaseQuery::InsertNewPassword($hash, $userPk, $this->m_db);
							$user = $lw->GetUserName();
							if ($lw->GetCookie($lw->m_usernameCookie) === $user) {
								$lw->SetCookie($lw->m_usernameCookie, $user);
								$lw->SetCookie($lw->m_passwordCookie, $hash);
							}
							return self::EVERYTHING_WENT_BETTER_THEN_EXPECTED;
						}
						return self::INVALID_OLD_PASSWORD;
					}
					return self::INVALID_USER;
				}
				return self::INVALID_NEW_PASSWORD_NO_MATCH;
			}
			return self::INVALID_NEW_PASSWORD;
		}
		
		/**
		 * @return boolean
		 */
		public function GetFriendship ($userPk, $lw) {
			$fsa =  DatabaseQuery::SelectFriendship($lw->GetUserPk(), $userPk, $this->m_db);
			$fsb =  DatabaseQuery::SelectFriendship($userPk, $lw->GetUserPk(), $this->m_db);			
			
			foreach($fsb as $value ) {
				$fsa[] = $value;
			}
			
			return $fsa;
		}
		
		/**
		 * @param LoginView
		 * @param ProfileView
		 */
		public function SendFriendRequest(\Qzn\View\LoginView $lw, \Qzn\View\ProfileView $pw) {
			DatabaseQuery::SendFriendRequestQuery($lw->GetUserPk(), $pw->GetAddFriend(), $this->m_db);
		}
	}
?>